package com.tanhua.sso.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.LogApi;
import com.tanhua.dubbo.server.pojo.Log;
import com.tanhua.sso.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author zwy
 */
@Service
public class LogService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference(version = "1.0.0")
    private LogApi logApi;

    // 模拟手机型号
    private static final String[] mockDevices = {
            "iphone20proMax", "iphone30proMax", "iphone40proMax", "iphone50proMax", "iphone60proMax", "iphone70proMax"
    };
    // 模拟操作地点
    private static final String[] mockCities = {
            "北京", "上海", "广州", "深圳", "杭州", "合肥"
    };

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 功能描述: saveLog   保存日志
     *
     * @param
     * @Return: {@link String}
     * @throws:
     * @Author: zwy
     * @Date: 2020/12/24 19:43
     */
    public String saveLog(String token) {
        try {
            String redisTokenKey = "TOKEN_" + token;
            String cacheData = redisTemplate.opsForValue().get(redisTokenKey);
            if (StringUtils.isEmpty(cacheData)) {
                return null;
            }
            User user = MAPPER.readValue(cacheData, User.class);
            Log log = new Log();
            log.setId(new ObjectId());
            log.setUserId(user.getId());
            log.setLogTime(System.currentTimeMillis());
            log.setPlace(mockCities[RandomUtil.randomInt(0, mockCities.length - 1)]);
            log.setEquipment(mockDevices[RandomUtil.randomInt(0, mockDevices.length - 1)]);
            this.logApi.saveLog(log);
            return log.getId().toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
